import router from "./router";
import Message from "element-ui/packages/message/src/main";

// 路由判断登录 根据路由配置文件的参数
router.beforeEach((to, from, next) => {
    console.log('上一个页面：', from)
    console.log('下一个页面：', to);
    let _this = this;
    let token = localStorage.getItem("JWT_TOKEN");
    let role = localStorage.getItem('role')
    console.log('role：', role)
  if (to.matched.some(record => record.meta.requireAuth)) { // 判断该路由是否需要登录权限
    console.log("-----路由判断登录请求JWT_TOKEN-------" + token);
      console.log('to.meta.roles.includes(\'user\')',to.meta.roles.includes('user'));
      console.log('to.meta.roles.includes(\'admin\')',to.meta.roles.includes('admin'));
      // 判断当前的token是否存在 ； 登录存入的token
    if (token != null) { // token存在时
        if (to.meta.roles.length !== 0) {
            for (let i = 0; i < to.meta.roles.length; i++) {
                console.log("to.meta.roles[i]",to.meta.roles[i]);
                if (role === to.meta.roles[i]) {
                    console.log("角色验证成功！")
                    next();
                    break
                } else if (i === to.meta.roles.length - 1) {
                    next({
                        path: '/Error'
                    })
                }
            }
        } else {
            next()
        }
    }
    else {
        console.log("=======token不存在=========");
        if(to.meta.roles.includes('user')){
            Message({
                message: "未登录，请登录后重试",
                type: 'danger'
            });
            next({
                path: '/area'
            })
        }
        else if(to.meta.roles.includes('admin')){
            console.log("admin登录信息过期，请重新登录");
            Message({
                message: "未登录，请登录后重试",
                type: 'danger'
            });
            next({
                path: '/adminLogin'
            })

        }
    }
  } else {
    next();
  }
});